package one.queue;

/**
 * 循环队列
 * 思路：
 * 1）使用数组实现
 * 2）队空：tail=head; 队满：(tail+1)%n=head
 */
public class CircularQueue {
    private int[] cq;
    private int head; //下标
    private int tail;

    public CircularQueue(int k){
        this.cq = new int[k + 1]; //循环队列会浪费一个存储空间
        this.head = 0;
        this.tail = 0;
    }
    public boolean isEmpty(){
        return tail == head;
    }
    public boolean isFull(){
        return (tail + 1) % cq.length == head;
    }
    public boolean insert(int value){
        if(isFull()){
            return false;
        }else {
            cq[tail] = value;
            tail = ((tail == cq.length - 1) ? 0 : (tail + 1));
            return true;
        }
    }
    public boolean delete(){
        if(isEmpty()){
            return false;
        }else {
            head = ((head == cq.length - 1) ? 0 : (head + 1));
            return true;
        }
    }
    public int get(){
        if(isEmpty()){
            return  -1;
        }else{
            return cq[head];
        }
    }

    public static void main(String[] args) {
        CircularQueue cq = new CircularQueue(3);
        cq.insert(1);
        cq.insert(2);
        cq.insert(3);
        System.out.println(cq.isFull());
        while (!cq.isEmpty()){
            System.out.println(cq.get());
            cq.delete();
        }
        System.out.println(cq.isEmpty());
    }
}
